package lambda;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class StreamOperations {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("张三", 25, "男"),
                new Person("李四", 20, "男"),
                new Person("王五", 30, "女"),
                new Person("赵六", 28, "男"),
                new Person("钱七", 22, "女")
        );

        // 1. 过滤与收集
        List<Person> adults = people.stream()
                .filter(p -> p.getAge() >= 25)  // 过滤25岁以上
                .collect(Collectors.toList());  // 收集结果

        System.out.println("25岁以上的人：" + adults);

        // 2. 映射
        List<String> names = people.stream()
                .map(Person::getName)  // 提取姓名
                .collect(Collectors.toList());

        System.out.println("\n所有人名：" + names);

        // 3. 排序
        List<Person> sortedByAge = people.stream()
                .sorted((p1, p2) -> p1.getAge() - p2.getAge())  // 按年龄排序
                .collect(Collectors.toList());

        System.out.println("\n按年龄排序：" + sortedByAge);

        // 4. 聚合计算
        int totalAge = people.stream()
                .mapToInt(Person::getAge)  // 转换为int流
                .sum();  // 求和

        Optional<Person> oldest = people.stream()
                .max((p1, p2) -> p1.getAge() - p2.getAge());  // 求最大值

        System.out.println("\n总年龄：" + totalAge);
        oldest.ifPresent(p -> System.out.println("最大年龄：" + p.getAge()));

        // 5. 分组
        java.util.Map<String, List<Person>> groupedByGender = people.stream()
                .collect(Collectors.groupingBy(Person::getGender));  // 按性别分组

        System.out.println("\n按性别分组：" + groupedByGender);
    }
}

// 扩展Person类
class Person {
    private String name;
    private int age;
    private String gender;

    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public String getGender() { return gender; }

    @Override
    public String toString() {
        return name + "(" + age + ")";
    }
}
